import { useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { message } from 'antd';
import request from '@/utils/request';

interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message?: string;
  code?: number;
}

interface PaginationParams {
  current?: number;
  pageSize?: number;
}

interface UseTableWithSearchOptions<T, P> {
  /** API 请求地址 */
  requestUrl: string;
  /** 默认分页大小 */
  defaultPageSize?: number;
  /** 创建新记录的模板 */
  createRecordTemplate?: () => Partial<T>;
  /** 自定义请求参数处理 */
  customParamsHandler?: (params: PaginationParams & P) => any;
}

/**
 * 表格与搜索的自定义 Hook
 * @template T - 数据类型
 * @template P - 搜索参数类型
 */
const useTableWithSearch = <T extends Record<string, any>, P extends Record<string, any>>(
  options: UseTableWithSearchOptions<T, P>
) => {
  const {
    requestUrl,
    defaultPageSize = 10,
    createRecordTemplate,
    customParamsHandler,
  } = options;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState<P>({} as P);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  });

  // 加载表格数据
  const loadTableData = async (params: PaginationParams & P) => {
    setLoading(true);
    try {
      const finalParams = customParamsHandler ? customParamsHandler(params) : {
        page: params.current,
        pageSize: params.pageSize,
        ...params,
      };

      const { data } = await request.get<ApiResponse<{
        list: T[];
        total: number;
        page: number;
        pageSize: number;
      }>>(`${requestUrl}/list`, {
        params: finalParams,
      });

      if (data?.success) {
        setDataSource(data.data.list);
        setPagination(prev => ({
          ...prev,
          total: data.data.total,
        }));
      }
    } catch (error) {
      message.error('获取列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = async (values: P) => {
    setSearchParams(values);
    const params = {
      ...values,
      current: 1,
      pageSize: pagination.pageSize,
    };
    await loadTableData(params);
    return true;
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({} as P);
    const params = {
      current: 1,
      pageSize: pagination.pageSize,
    };
    loadTableData(params);
  };

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
    loadTableData({
      ...searchParams,
      current: page,
      pageSize,
    });
  };

  // 处理保存
  const handleSave = async (key: React.Key, row: T) => {
    const { id, ...data } = row as any;
    const isNew = id.toString().startsWith('temp_');
    const url = isNew ? `${requestUrl}/create` : `${requestUrl}/update`;
    const submitData = isNew ? data : row;

    try {
      const { data: resData } = await request.post<ApiResponse>(url, submitData);
      if (resData.success) {
        message.success(isNew ? '创建成功' : '更新成功');
        loadTableData({
          ...searchParams,
          current: pagination.current,
          pageSize: pagination.pageSize,
        });
        return true;
      }
      return false;
    } catch (error) {
      message.error(isNew ? '创建失败' : '更新失败');
      return false;
    }
  };

  return {
    actionRef,
    formRef,
    dataSource,
    loading,
    editableKeys,
    pagination,
    setEditableRowKeys,
    handleSearch,
    handleReset,
    handlePaginationChange,
    handleSave,
    createRecordTemplate,
  };
};

export default useTableWithSearch; 